<?php
	include('db-api/txt-db-api.php');

	function user_found()
	{
		if(isset($_SESSION['user']))
			return true;
		if(!isset($_COOKIE['eam_eclass_login']))
			return false;
		foreach($_COOKIE['eam_eclass_login'] as $name => $value)
			$_SESSION[$name] = $value;
		return true;
	}
	
	function username_found($db)
	{
		$rs = $db->executeQuery('SELECT * FROM Users WHERE Username = \'' . $_POST['username'] . '\'');
		if($rs->next())
		{
			return true;
		}
		return false;
	}
	
	function email_found($db)
	{
		$rs = $db->executeQuery('SELECT * FROM Users WHERE Email = \'' . $_POST['email'] . '\'');
		if($rs->next())
		{
			return true;
		}
		return false;
	}
	
	function register(&$error)
	{
		if(!isset($_POST['firstname']) || $_POST['firstname'] == '')
			$error = '* Δε δώσατε όνομα<br />';
		if(!isset($_POST['lastname']) || $_POST['lastname'] == '')
			$error = $error . '* Δε δώσατε επώνυμο<br />';
		if(!isset($_POST['username']) || $_POST['username'] == '')
			$error = $error . '* Δε δώσατε όνομα χρήστη<br />';
		if(!isset($_POST['password']) || $_POST['password'] == '')
			$error = $error . '* Δε δώσατε συνθηματικό<br />';
		if(!isset($_POST['email']) || $_POST['email'] == '')
			$error = $error . '* Δε δώσατε ηλεκτρονική διεύθυνση<br />';
		if(!isset($_POST['kind']) || $_POST['kind'] == '')
			$error = $error . '* Δε δώσατε είδος χρήστη';
			
		if($error != '')
			return;
		
		$db = new Database('Eclass');
		if(username_found($db) == true)
			$error = '* Το όνομα χρήστη υπάρχει ήδη<br />';
		if(email_found($db) == true)
			$error = $error . '* Η ηλεκτρονική διεύθυνση υπάρχει ήδη';
			
		if($error != '')
			return;
		
		$position = 'Stud';
		if($_POST['kind'] == 'Φοιτητής')
			$position = 'Stud';
		else if($_POST['kind'] == 'Καθηγητής')
			$position = 'Prof';
		$db->executeQuery('INSERT INTO Users VALUES (' . $_POST['firstname'] . ',' . $_POST['lastname']
		. ',' . $_POST['username'] . ',' . $_POST['password'] . ',' . $_POST['email'] . ',' . $position
		. ')');
		$_SESSION['user'] = $_POST['firstname'] . ' ' . $_POST['lastname'];
		$_SESSION['position'] = $position;
		$_SESSION['username'] = $_POST['username'];

		$to = $_POST['email'];
		$body = 'Όνομα χρήστη: ' . $_POST['username'] . '   Συνθηματικό: ' . $_POST['password'];
		$header = 'From: e-class team <std06138@di.uoa.gr>';
		$subject = 'register to e-class';
		mail($to, $subject, $body, $header);

		header('Location: index.php');
	}
	
	if(user_found() == true)
		header('Location: index.php');
	else
	{
		$error = '';
		if(isset($_GET['action']) && $_GET['action'] == 'register')
			register($error);
	}
?>
